package cn.kgc.service.impl;

import cn.kgc.client.RestDmCinemaClient;
import cn.kgc.client.RestDmImageClient;
import cn.kgc.client.RestDmItemClient;
import cn.kgc.client.RestDmItemTypeClient;
import cn.kgc.exception.ItemErrorCode;
import cn.kgc.pojo.DmCinema;
import cn.kgc.pojo.DmImage;
import cn.kgc.pojo.DmItem;
import cn.kgc.pojo.DmItemType;
import cn.kgc.service.HomeService;
import cn.kgc.utils.BaseException;
import cn.kgc.utils.Constants;
import cn.kgc.utils.DateUtil;
import cn.kgc.utils.EmptyUtils;
import cn.kgc.vo.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static cn.kgc.utils.Constants.Item.ItemTypeLevel.level1;

//添加@Service让spring能读取得到，使其成为spring的bean
@Service
@Slf4j
public class HomeServiceImpl implements HomeService {
    //调用生产者用RestDmItemClient
    @Resource
    RestDmItemClient restDmItemClient;
    @Resource
    RestDmImageClient restDmImageClient;
    @Resource
    RestDmItemTypeClient restDmItemTypeClient;
    @Resource
    RestDmCinemaClient restDmCinemaClient;

    //核心   业务流程
    //1.获取isBanner=1的商品，isBanner=1的商品是热推，热推有可能有N件，取前五件商品作为轮播----？dm_item--->dm_item
    //2.获取到热推的商品，获取热推的图片 ----》dm_item--id--->ID+TYPE+categoryID--》图片 --->   dm_base--->dm_image
    //3.如果没有图片----》默认图片展示。
    //4.封装vo返回


    //查询首页轮播图
    @Override
    public List<HotItemVo> queryBanner() throws Exception {
        //1.获取isBanner=1的商品，isBanner=1的商品是热推，热推有可能有N件，取前五件商品作为轮播----？dm_item--->dm_item
        Map map = new HashMap<>();
        map.put("isBanner", 1);
        map.put("beginPos", new Integer(0));
        map.put("pageSize", new Integer(5));

        //创建一个HotItemVo的list存放结果
        List<HotItemVo> list = new ArrayList<>();
        //指定这里为DmItem泛型
        List<DmItem> dmItemListByMap = restDmItemClient.getDmItemListByMap(map);
        if (dmItemListByMap == null) {
            return null;
        }

        //获取到热推的商品，获取热推的图片 ----》dm_item--id--->ID+TYPE+categoryID--》图片
        for (DmItem dmItem : dmItemListByMap) {
            HotItemVo hotItemVo = new HotItemVo();
            //导数据，将pojo导入到vo中，前提必须属性名，类型一致
            BeanUtils.copyProperties(dmItem, hotItemVo);
            //两个对象属性名或者类型不一致，又需要赋值，这时候就通过getter setter方法赋值
            hotItemVo.setItemId(dmItem.getId());

            //获取商品的热推图片，banner图---》，取到其中的一张轮播图就可以了
            DmImage dmImage = restDmImageClient.getDmImage_DefaultImage(dmItem.getId(),
                    Constants.Image.ImageType.carousel, Constants.Image.ImageCategory.item).get(0);
            //然后拷贝这个轮播图8
            BeanUtils.copyProperties(dmImage, hotItemVo);
            //拷贝完的数据放进list中
            list.add(hotItemVo);
        }
        //最终返回list结果集
        return list;
    }

    /**
     * 业务流程： 获取所有的商品分类
     * 1.获取所有节目分类
     * 2.遍历分类节目根据等级分类和父类id，进行等级划分
     * 3.根据父类id和子类id 去获取节目，并查询它是否为热门节目
     *
     * @return
     * @throws Exception
     */
    @Override
    public List<HomeItemTypeVo> queryAllType() throws Exception {
        Map map = new HashMap<>();
        //1.1添加条件 只获取一级分类
        map.put("level", "1");
        List<DmItemType> dmItemTypeListByMap = restDmItemTypeClient.getDmItemTypeListByMap(map);
        List<HomeItemTypeVo> homeItemTypeVos = new ArrayList<>();
        //1.2非空判断
        if (CollectionUtils.isEmpty(dmItemTypeListByMap)) {
            //找不到商品分类
            throw new BaseException(ItemErrorCode.ITEM_CATEGORY_NOT_FOUND);
        }
        log.info("一级分类" + homeItemTypeVos);
        //返回数据
        return dmItemTypeListByMap.stream().map(dmItemType -> {
            //2.创建所有的商品分类Vo
            HomeItemTypeVo homeItemTypeVo = new HomeItemTypeVo();
            //2.1拷贝数据,将1级分类赋值到vo
            BeanUtils.copyProperties(dmItemType, homeItemTypeVo);
            //2.2 定义一个查询子分类方法
            List<HomeItemTypeVo> children = null;
            try {
                children = getChilren(dmItemType.getId());
                homeItemTypeVo.setChildren(children);
                Map<String, Object> map1 = new HashMap<>();
                //如果是一级分类
                if (map.get("level").equals(dmItemType.getLevel())) {
                    map1.put("itemType1Id", dmItemType.getId());
                }
                //如果是二级分类
                if (map.get("level").equals(dmItemType.getLevel())) {
                    map1.put("itemType2Id", dmItemType.getId());
                }
                //是否热门 1是热推(可以封装为常量)
                map.put("isRecommend", Constants.Item.ItemBanner.isBanner);
                //获取商品详情
                List<DmItem> dmItemListByMap = restDmItemClient.getDmItemListByMap(map1);
                List<HotItemsVo> list = new ArrayList<>();
                for (DmItem dmItem : dmItemListByMap) {
                    //创建热门节目vo
                    HotItemsVo hotItemsVo = new HotItemsVo();
                    //赋值分类id
                    hotItemsVo.setId(dmItemType.getId());
                    //赋值热门节目
                    hotItemsVo.setItemName(dmItem.getItemName());
                    //赋值最低价格
                    hotItemsVo.setMinPrice(dmItem.getMinPrice());
                    //根据商品id查询url，获取图片
                    //可以获取所有的数据,但是需要再叠一层for 所以get(0)
                    DmImage dmImage = restDmImageClient.getDmImage_DefaultImage(dmItem.getId(),
                            Constants.Image.ImageType.poster,
                            Constants.Image.ImageCategory.item).get(0);
                    hotItemsVo.setImgUrl(dmImage.getImgUrl());
                    list.add(hotItemsVo);
                }
                homeItemTypeVo.setHotItems(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return homeItemTypeVo;
        }).collect(Collectors.toList());
    }

    //获取子分类
    private List<HomeItemTypeVo> getChilren(Long id) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //1.添加 条件 parent=父类id
        map.put("parent", id);
        //2.获取数据
        List<DmItemType> dmItemTypeListByMap = restDmItemTypeClient
                .getDmItemTypeListByMap(map);
        //3.非空判断
        if (CollectionUtils.isEmpty(dmItemTypeListByMap)) {
            //没有子分类
            throw new BaseException(ItemErrorCode.ITEM_CATEGORY_CHILDREN_NOT_FOUND);
        }
        return dmItemTypeListByMap.stream().map(dmItemType -> {
            HomeItemTypeVo categoryVo = new HomeItemTypeVo();
            BeanUtils.copyProperties(dmItemType, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());

    }

    //获取首页横向导航数据
    @Override
    public List<List<ItemTransverseTypeVo>> queryTransverse() throws Exception {
        //1.先获取商品分类
        Map<String, Object> goodsMap = new HashMap<>();
        //1.1添加条件 只获取横向分类
        goodsMap.put("level", level1);
        List<DmItemType> dmItemTypeListByMap = restDmItemTypeClient.getDmItemTypeListByMap(goodsMap);

        //创建首页横向导航数据Vos
        List<ItemTransverseTypeVo> itemTransverseTypeVos = new ArrayList<>();

        //1.2非空判断
        if (CollectionUtils.isEmpty(dmItemTypeListByMap)) {
            //找不到商品分类
            throw new BaseException(ItemErrorCode.ITEM_CATEGORY_NOT_FOUND);
        }


        return dmItemTypeListByMap.stream().map(dmItemType -> {


            try {

                for (DmItemType dmitemType : dmItemTypeListByMap) {

                    ItemTransverseTypeVo transverseTypeVo = new ItemTransverseTypeVo();
                    //2.1拷贝数据
                    BeanUtils.copyProperties(dmItemType, transverseTypeVo);
                    itemTransverseTypeVos.add(transverseTypeVo);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return itemTransverseTypeVos;
        }).collect(Collectors.toList());

    }


//今日推荐

    /**
     * 1、获取isRecommend=1的商品，isRecommend=1为今日推荐商品，取前五件
     * 2、获取今日推荐图片url    dm_item--id--->ID+TYPE+categoryID--》图片 --->   dm_base--->dm_image
     * 3、如果没有图片----》默认图片展示。
     * 4、封装vo返回
     *
     * @return
     */
    @Override
    public List<HotItemsVo> queryTodayRecommend() throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("isRecommend", Constants.Item.ItemRecommend.isRecommend);
        map.put("beginPos", new Integer(0));
        map.put("pageSize", new Integer(5));

        List<HotItemsVo> hotItemVoList = new ArrayList<>();
        List<DmItem> dmItemListByMap = restDmItemClient.getDmItemListByMap(map);

        if (CollectionUtils.isEmpty(dmItemListByMap)) {
            throw new BaseException(ItemErrorCode.ITEM_No_EXIST);
        }

        //遍历数据
        for (DmItem dmItem : dmItemListByMap) {
            HotItemsVo hotItemsVo = new HotItemsVo();
            BeanUtils.copyProperties(dmItem, hotItemsVo);
            hotItemsVo.setId(dmItem.getId());

            //获取商品的今日推荐图片
            DmImage dmImage = restDmImageClient.getDmImage_DefaultImage(dmItem.getId(), Constants.Image.ImageType.carousel, Constants.Image.ImageCategory.item).get(0);
            BeanUtils.copyProperties(dmImage, hotItemsVo);
            hotItemVoList.add(hotItemsVo);
        }
        return hotItemVoList;
    }


    /**
     * 即将开售
     * 获取state=2的商品，state=2的商品为预售/即将开售
     *
     * @throws Exception
     */
    @Override
    public List<HotItemsVo> queryToSaleItem() throws Exception {
        Map map = new HashMap();
        map.put("state", 2);
        map.put("beginPos", new Integer(0));
        map.put("pageSize", new Integer(5));
        //获取集合信息
        List<DmItem> dmItemListByMap = restDmItemClient.getDmItemListByMap(map);
        List<HotItemsVo> hotItemVoList = new ArrayList<>();

        if (EmptyUtils.isEmpty(dmItemListByMap)) {
            throw new BaseException(ItemErrorCode.ITEM_No_EXIST);
        }

        //遍历数据
        for (DmItem dmItem : dmItemListByMap) {
            HotItemsVo hotItemsVo = new HotItemsVo();
            BeanUtils.copyProperties(dmItem, hotItemsVo);
            //获取商品的即将开售图片
            DmImage dmImage = restDmImageClient.getDmImage_DefaultImage(dmItem.getId(),
                    Constants.Image.ImageType.carousel,
                    Constants.Image.ImageCategory.item).get(0);
            BeanUtils.copyProperties(dmImage, hotItemsVo);
            hotItemVoList.add(hotItemsVo);

        }
        return hotItemVoList;
    }

    //获取商品图片
    public List<DmImage> getImage(DmItem dmItem) throws Exception {
        Map map = new HashMap<>();
        map.put("targetId", dmItem.getId());
        List<DmImage> dmImageListByMap = restDmImageClient.getDmImageListByMap(map);
        if (CollectionUtils.isEmpty(dmImageListByMap) || dmImageListByMap.size() == 0) {
            DmImage dmImage = new DmImage();
            dmImage.setImgUrl(Constants.DEFAULT_CAROUSEL);
        }
        return dmImageListByMap;
    }

    //首页返回不同楼层展示数据
    @Override
    public List<ItemFloorLevelVo> queryFloorItems() throws Exception {
        //1.1获取全部1级分类
        Map map = new HashMap();
        map.put("level", level1);
        List<DmItemType> dmItemTypeListByMap = restDmItemTypeClient.getDmItemTypeListByMap(map);
        //添加放Vo的list
        List<ItemFloorLevelVo> itemLevelVoList = new ArrayList<>();
        if (CollectionUtils.isEmpty(dmItemTypeListByMap)) {
            throw new BaseException(ItemErrorCode.ITEM_CATEGORY_NOT_FOUND);
        }

        //遍历
        for (DmItemType itemType : dmItemTypeListByMap) {
            ItemFloorLevelVo itemFloorLevelVo = new ItemFloorLevelVo();
            BeanUtils.copyProperties(itemType, itemFloorLevelVo);
            //set Id
            itemFloorLevelVo.setItemTypeId(itemType.getId());
            //set itemTypeName
            itemFloorLevelVo.setItemTypeName(itemType.getItemType());
            //根据类型获取该类型排名前五的商品信息
            List<ItemRecommendVo> itemRecommendVos = avgScoreSort(itemType.getId());
            //排名前5的节目
            itemFloorLevelVo.setItems(itemRecommendVos);
            itemLevelVoList.add(itemFloorLevelVo);

        }

        return itemLevelVoList;
    }

    //1.2获取该类型积分排名前五的节目
    private List<ItemRecommendVo> avgScoreSort(Long id) throws Exception {
        Map map = new HashMap();
        map.put("itemType1Id", new Long(id));
        map.put("beginPos", new Integer(0));
        map.put("pageSize", new Integer(5));
        List<DmItem> dmItemListByScoreSort = restDmItemClient.getDmItemListByMap(map);
        List<ItemRecommendVo> itemRecommendVoList = new ArrayList<>();
        //非空判断
        if (CollectionUtils.isEmpty(dmItemListByScoreSort)) {
            throw new BaseException(ItemErrorCode.ITEM_CATEGORY_NOT_FOUND);
        }
        for (DmItem dmItem : dmItemListByScoreSort) {
            ItemRecommendVo itemRecommendVo = new ItemRecommendVo();
            BeanUtils.copyProperties(dmItem, itemRecommendVo);
            //set 开始时间
            itemRecommendVo.setStartDate(DateUtil.format(dmItem.getStartTime()));
            //set 结束时间
            itemRecommendVo.setEndDate(DateUtil.format(dmItem.getEndTime()));

            //获取商品图片
            DmImage dmImage = restDmImageClient.getDmImage_DefaultImage(dmItem.getId(),
                    Constants.Image.ImageType.carousel,
                    Constants.Image.ImageCategory.item).get(0);
            itemRecommendVo.setImgUrl(dmImage.getImgUrl());

            //获取城市信息
            DmCinema address = getAddress(dmItem.getCinemaId());
            BeanUtils.copyProperties(address, itemRecommendVo);

            itemRecommendVoList.add(itemRecommendVo);
        }
        return itemRecommendVoList;

    }

    //1.3获取城市信息
    private DmCinema getAddress(Long cinemaId) throws Exception {
        DmCinema dmCinema = restDmCinemaClient.getDmCinemaById(cinemaId);
        return dmCinema;
    }

    //不同分类排行
    @Override
    public List<HomeItemRangVo> queryHotItems(Integer itemTypeId) throws Exception {
        //根据分类获取该分类的热门推荐 isRecommend=1的商品为推荐商品
        Map map = new HashMap<>();
        map.put("itemType1Id", itemTypeId);
        map.put("isRecommend", 1);
        List<DmItem> dmItemListByMap = restDmItemClient.getDmItemListByMap(map);

        List<HomeItemRangVo> homeItemRangVoList = new ArrayList<>();
        if (CollectionUtils.isEmpty(dmItemListByMap)) {
            throw new BaseException(ItemErrorCode.ITEM_NO_TYPE_SHOWS);
        }
        for (DmItem dmItem : dmItemListByMap) {
            HomeItemRangVo homeItemRangVo = new HomeItemRangVo();

            //获取影院信息
            DmCinema dmCinemaById = restDmCinemaClient.getDmCinemaById(dmItem.getCinemaId());
            homeItemRangVo.setId(dmItem.getId());
            homeItemRangVo.setAreaId(dmCinemaById.getAreaId());
            homeItemRangVo.setItemName(dmItem.getItemName());
            homeItemRangVo.setAreaName(dmCinemaById.getAreaName());
            homeItemRangVoList.add(homeItemRangVo);
        }

        return homeItemRangVoList;
    }

    //根据token返回用户信息
    @Override
    public List<ItemCurrentUserByTokenVo> loadCurrentUserByToken() {
        return null;
    }


}